<template>
  <div class="app-container">
    <el-dialog :model-value="itemsVisible" title="选择指标单" :append-to-body="true" width="95%" height="1000px" @close="closeBtn">
      <div class="filter-container">
        <el-form :inline="true" :model="listQuery" class="demo-form-inline">
          <el-form-item prop="kpiCode" label="指标编码">
            <el-input v-model="listQuery.kpiCode" placeholder="指标编码" @keyup.enter="handleFilter" />
          </el-form-item>
          <el-form-item prop="kpiName" label="指标名称">
            <el-input v-model="listQuery.kpiName" placeholder="指标名称" @keyup.enter="handleFilter" />
          </el-form-item>
          <el-form-item prop="source" label="指标来源">
            <el-select v-model="listQuery.source" class="m-2" placeholder="请选择">
              <el-option key="" label="全部" value="" />
              <el-option v-for="item in getDictList('ExpenditureKpiSource')" :key="item.key" :label="`${item.key} - ${item.value}`" :value="item.key" />
            </el-select>
          </el-form-item>
          <el-form-item prop="year" label="预算年度">
            <el-date-picker v-model="listQuery.year" type="year" placeholder="请选择" value-format="YYYY" />
          </el-form-item>
          <el-form-item prop="payType" label="支出类型">
            <el-select v-model="listQuery.payType" class="m-2" placeholder="请选择">
              <el-option key="" label="全部" value="" />
              <el-option v-for="item in getDictList('ExpenditureKpiPayType')" :key="item.key" :label="`${item.key} - ${item.value}`" :value="item.key" />
            </el-select>
          </el-form-item>
          <el-form-item prop="fundType" label="经费类型">
            <el-select v-model="listQuery.fundType" class="m-2" placeholder="请选择">
              <el-option key="" label="全部" value="" />
              <el-option v-for="item in getDictList('ExpenditureKpiFundType')" :key="item.key" :label="`${item.key} - ${item.value}`" :value="item.key" />
            </el-select>
          </el-form-item>
          <el-form-item prop="organizationId" label="负责部门">
            <Organization v-model="listQuery.organizationId" keyName="id" keyShow="organizationName" placeholder="负责部门" title="部门查询" />
          </el-form-item>
          <el-form-item prop="managerId" label="负责人">
            <User v-model="listQuery.managerId" keyName="id" keyShow="name" placeholder="负责人" title="用户查询" />
          </el-form-item>
          <el-form-item prop="state" label="状态">
            <el-radio-group v-model="listQuery.state" disabled>
              <el-radio-button label="" key="">全部</el-radio-button>
              <el-radio-button v-for="(item,index) in getEnumList('ExpenditureAdjustmentState')" :label="item.key" :key="index">{{item.value}}</el-radio-button>
            </el-radio-group>
          </el-form-item>
          <el-form-item prop="isEconomic" label="按经济分类控制金额">
            <el-radio-group v-model="listQuery.isEconomic">
              <el-radio-button label="" key="">全部</el-radio-button>
              <el-radio-button v-for="(item,index) in getEnumList('CommonYesNo')" :label="item.key" :key="index">{{item.value}}</el-radio-button>
            </el-radio-group>
          </el-form-item>
          <el-form-item>
            <el-button type="success" icon="Search" @click="handleFilter">
              查询
            </el-button>
          </el-form-item>
        </el-form>
      </div>
      <div class="app-container">
        <el-table v-loading="listLoading"
                  :data="dataList"
                  border
                  fit
                  highlight-current-row
                  tooltip-effect="dark"
                  style="width: 100%; margin-bottom: 20px;">
          <el-table-column align="center" type="index" label="序号" width="60px" />
          <el-table-column align="center" label="指标编码" prop="kpiCode" min-width="240px"></el-table-column>
          <el-table-column align="center" label="指标名称" prop="kpiName" min-width="200px" show-overflow-tooltip></el-table-column>
          <el-table-column align="center" label="预算总金额" min-width="120px">
            <template v-slot="{row}"><MoneyTag :money="row.amount" /></template>
          </el-table-column>
          <el-table-column align="center" label="总调整金额" min-width="120px">
            <template v-slot="{row}"><MoneyTag :money="row.totalAdjustmentAmount" /></template>
          </el-table-column>
          <el-table-column align="center" label="总下达金额(含初始下达)" min-width="120px">
            <template v-slot="{row}"><MoneyTag :money="row.totalQuotaAmount" /></template>
          </el-table-column>
          <el-table-column align="center" label="可用金额" min-width="120px">
            <template v-slot="{row}">
              <span style="font-weight: bold;"><MoneyTag :elTagType="colorOfMoney(row.availableAmount)" :money="row.availableAmount" /></span>
            </template>
          </el-table-column>
          <el-table-column align="center" label="总申请金额" min-width="120px">
            <template v-slot="{row}"><MoneyTag :money="row.totalApplicationAmount" /></template>
          </el-table-column>
          <el-table-column align="center" label="总报账金额(含初始报账)" min-width="120px">
            <template v-slot="{row}"><MoneyTag :money="row.totalReimbursementAmount" /></template>
          </el-table-column>

          <el-table-column align="center" label="状态" prop="state" min-width="120px" show-overflow-tooltip>
            <template v-slot="{row}">
              <EnumTag :enum-list="getEnumList('ExpenditureKpiState')" :enum-key="row.state" />
            </template>
          </el-table-column>
          <el-table-column align="center" label="指标来源" prop="source" min-width="180px" show-overflow-tooltip>
            <template v-slot="{row}">
              <DictTag :dict-list="getDictList('ExpenditureKpiSource')" :dict-key="row.source"/>
            </template>
          </el-table-column>
          <el-table-column align="center" label="支出类型" prop="payType" min-width="140px" show-overflow-tooltip>
            <template v-slot="{row}">
              <DictTag :dict-list="getDictList('ExpenditureKpiPayType')" :dict-key="row.payType"/>
            </template>
          </el-table-column>
          <el-table-column align="center" label="经费类型" prop="fundType" min-width="170px" show-overflow-tooltip>
            <template v-slot="{row}">
              <DictTag :dict-list="getDictList('ExpenditureKpiFundType')" :dict-key="row.fundType"/>
            </template>
          </el-table-column>
          <el-table-column align="center" label="项目负责人部门" prop="organizationId" min-width="130px" show-overflow-tooltip>
            <template v-slot="{row}">{{ showIdLabel(organizationList, row.organizationId, 'organizationName') }}</template>
          </el-table-column>
          <el-table-column align="center" label="项目负责人" prop="managerId" min-width="130px" show-overflow-tooltip>
            <template v-slot="{row}">{{ showIdLabel(userList, row.managerId, 'name') }}</template>
          </el-table-column>
          <el-table-column align="center" label="创建时间" width="180px" prop="createTime" sortable show-overflow-tooltip>
            <template v-slot="{row}"><DateTag :timestamp="row.createTime" /></template>
          </el-table-column>
          <el-table-column align="center" label="最后修改时间" width="180px" prop="updateTime" sortable show-overflow-tooltip>
            <template v-slot="{row}"><DateTag :timestamp="row.updateTime" /></template>
          </el-table-column>
          <el-table-column label="选择指标" width="150" align="center" fixed="right">
            <template v-slot="{row}">
              <el-radio :label="row.id" v-model="tableRadio" border @click="handleCurrentChange($event, row)">选择</el-radio>
            </template>
          </el-table-column>
        </el-table>
        <pagination v-model:total="total" v-model:page="listQuery.pageNum" v-model:limit="listQuery.pageSize" @pagination="getList" class="pagination-model" />
        <div style="text-align:right;margin: 1.875rem 0;">
          <el-button type="danger" @click="closeBtn">关闭</el-button>
          <el-button type="primary" @click="onSureBtn">确定</el-button>
        </div>
      </div>
    </el-dialog>
  </div>
</template>
<script setup>
import {ref, watch} from 'vue'
import {doGet} from "@/config/http";
import {
  svc,
  getDictList,
  getEnumList,
  alertErrorMsg,
  showIdLabel, getListPageSize
} from "@/config/common";
import useUserStore from "@/store/modules/user";
import {getUserId} from "@/config/cookie";
import User from "@/views/components/base/selectUser.vue";
import Organization from "@/views/components/base/selectOrganization.vue";
import initListStore from '@/store/modules/initList'

const props = defineProps({
  itemsVisible: {
    required: true,
    type: Boolean,
  },
  state: {
    required: false,
    type: String,
  },
  expenditureKpiId: {
    required: false,
    type: String,
  },
})

let dataList = ref([])
let tableRadio = ref('')
let listLoading = ref(true)
let total = ref(0)

let listQuery = ref({
  pageNum: 1,
  pageSize: 10,
  sortField: 'id',
  sortType: 'desc',
  kpiCode: null,
  kpiName: null,
  kpiDateStart: null,
  kpiDateEnd: null,
  year: null,
  payType: null,
  fundType: null,
  amount: null,
  organizationId: useUserStore().organization.organizationType !== '1' ? useUserStore().organization.id : '',
  managerId: useUserStore().organization.organizationType !== '1' ? getUserId() : '',
  expenditurePtypeId: null,
  expenditureFunctionalId: null,
  expenditureFiscalId: null,
  source: null,
  state: '2',
  createTimeStart: null,
  createTimeEnd: null,
  updateTimeStart: null,
  updateTimeEnd: null,
  totalAdjustmentAmount: 0, // 总调整金额
  totalQuotaAmount: 0, // 总下达金额
  totalApplicationAmount: 0, // 总申请金额
  totalReimbursementAmount: 0, // 总报账金额
  availableAmount: 0, // 可用金额
})
let radioRow = null

let governmentList = initListStore().governmentList
let organizationList = initListStore().organizationList
let userList = initListStore().userList

const emit = defineEmits(['close', 'expenditureKpiSelect'])

watch(() => [props.itemsVisible, props.expenditureKpiId], async vals => {
  if (vals[0] === true) {
    await getList()
    // await initList()
    if (vals[1]) {
      tableRadio.value = vals[1]
    }
  }
})

// async function initList() {
//   let p1 = doGet(svc, '/government/page', {pageSize: getListPageSize()}, false)
//   let p2 = doGet(svc, '/organization/page', {pageSize: getListPageSize()}, false)
//   let p3 = doGet(svc, '/user/page', {pageSize: getListPageSize()}, false)
//   let resArray = await Promise.all([p1, p2, p3])
//   governmentList.value = resArray[0]['records']
//   organizationList.value = resArray[1]['records']
//   userList.value = resArray[2]['records']
// }

// 获取数据
async function getList() {
  listLoading.value = true
  let res = await doGet(svc, '/customExpenditureKpis/queryExpenditureKpi', listQuery.value)
  listLoading.value = false
  total.value = parseInt(res['total'])
  dataList.value = res['records']
}

// 查询
async function handleFilter() {
  listQuery.value['pageNum'] = 1
  await getList()
}

// 关闭弹层
function closeBtn(val) {
  console.debug(val)
  emit('close')
}

// 选择
function handleCurrentChange(val, row) {
  radioRow = row
}

// 点确定
function onSureBtn() {
  if (!radioRow) {
    alertErrorMsg('请选择指标单')
    return
  }
  emit('expenditureKpiSelect', radioRow)
  emit('close')
}

function colorOfMoney(money) {
  if (money > 100) {
    return "success"
  }
  if (money > 0) {
    return "warning"
  }
  return "danger"
}
</script>
